<template>
  <div class="medicine-handle">
    <el-form
      ref="medicineFormRef"
      :model="medicineForm"
      :rules="medicineRules"
      label-width="100px"
    >
      <!-- 基础信息 -->
      <el-divider content-position="left">基础信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="药品编码" prop="medicineCode">
            <el-input
              v-model="medicineForm.medicineCode"
              placeholder="请输入药品编码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="药品名称" prop="name">
            <el-input v-model="medicineForm.name" placeholder="请输入药品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="通用名称" prop="genericName">
            <el-input v-model="medicineForm.genericName" placeholder="请输入通用名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="medicineForm.manufacturer" placeholder="请输入生产厂家" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="药品分类" prop="category">
            <el-select v-model="medicineForm.category" placeholder="请选择分类" style="width: 100%">
              <el-option label="西药" :value="1" />
              <el-option label="中药" :value="2" />
              <el-option label="中成药" :value="3" />
              <el-option label="生物制品" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="药品类型" prop="type">
            <el-select v-model="medicineForm.type" placeholder="请选择类型" style="width: 100%">
              <el-option label="处方药" :value="1" />
              <el-option label="非处方药" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规格" prop="specification">
            <el-input v-model="medicineForm.specification" placeholder="请输入规格" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="medicineForm.unit" placeholder="请输入单位" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="批准文号" prop="approvalNumber">
            <el-input v-model="medicineForm.approvalNumber" placeholder="请输入批准文号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="药品状态" prop="status">
            <el-select v-model="medicineForm.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="正常" :value="1" />
              <el-option label="停用" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 价格和库存信息 -->
      <el-divider content-position="left">价格和库存</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="进价" prop="purchasePrice">
            <el-input-number
              v-model="medicineForm.purchasePrice"
              :min="0"
              :precision="2"
              style="width: 100%"
              placeholder="请输入进价"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="售价" prop="sellingPrice">
            <el-input-number
              v-model="medicineForm.sellingPrice"
              :min="0"
              :precision="2"
              style="width: 100%"
              placeholder="请输入售价"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="初始库存" prop="stockQuantity">
            <el-input-number
              v-model="medicineForm.stockQuantity"
              :min="0"
              style="width: 100%"
              placeholder="请输入库存数量"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="安全库存" prop="safetyStock">
            <el-input-number
              v-model="medicineForm.safetyStock"
              :min="0"
              style="width: 100%"
              placeholder="请输入安全库存"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最大库存" prop="maxStock">
            <el-input-number
              v-model="medicineForm.maxStock"
              :min="0"
              style="width: 100%"
              placeholder="请输入最大库存"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 日期信息 -->
      <el-divider content-position="left">日期信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生产日期" prop="productionDate">
            <el-date-picker
              v-model="medicineForm.productionDate"
              type="date"
              placeholder="请选择生产日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期" prop="expiryDate">
            <el-date-picker
              v-model="medicineForm.expiryDate"
              type="date"
              placeholder="请选择有效期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 存储和说明信息 -->
      <el-divider content-position="left">存储和说明</el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="存储条件" prop="storageCondition">
            <el-input v-model="medicineForm.storageCondition" placeholder="请输入存储条件" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="用法用量" prop="dosage">
            <el-input
              v-model="medicineForm.dosage"
              type="textarea"
              :rows="3"
              placeholder="请输入用法用量"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="功能主治" prop="indications">
            <el-input
              v-model="medicineForm.indications"
              type="textarea"
              :rows="3"
              placeholder="请输入功能主治"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="不良反应" prop="adverseReactions">
            <el-input
              v-model="medicineForm.adverseReactions"
              type="textarea"
              :rows="2"
              placeholder="请输入不良反应"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="禁忌症" prop="contraindications">
            <el-input
              v-model="medicineForm.contraindications"
              type="textarea"
              :rows="2"
              placeholder="请输入禁忌症"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="注意事项" prop="precautions">
            <el-input
              v-model="medicineForm.precautions"
              type="textarea"
              :rows="2"
              placeholder="请输入注意事项"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="medicineForm.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        {{ isEdit ? '更新' : '添加' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addMedicine, updateMedicine } from '@/api/admin'

// 定义props
const props = defineProps({
  medicineData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['close'])

// 响应式数据
const submitLoading = ref(false)
const medicineFormRef = ref()

// 药品表单
const medicineForm = reactive({
  id: null,
  medicineCode: '',
  name: '',
  genericName: '',
  category: 1,
  type: 1,
  specification: '',
  unit: '',
  manufacturer: '',
  approvalNumber: '',
  purchasePrice: 0,
  sellingPrice: 0,
  stockQuantity: 0,
  safetyStock: 10,
  maxStock: 1000,
  productionDate: '',
  expiryDate: '',
  storageCondition: '',
  status: 1,
  dosage: '',
  indications: '',
  adverseReactions: '',
  contraindications: '',
  precautions: '',
  remark: ''
})

// 表单验证规则
const medicineRules = {
  medicineCode: [
    { required: true, message: '请输入药品编码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入药品名称', trigger: 'blur' }
  ],
  genericName: [
    { required: true, message: '请输入通用名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择药品分类', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择药品类型', trigger: 'change' }
  ],
  specification: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  manufacturer: [
    { required: true, message: '请输入生产厂家', trigger: 'blur' }
  ],
  sellingPrice: [
    { required: true, message: '请输入售价', trigger: 'blur' }
  ],
  stockQuantity: [
    { required: true, message: '请输入初始库存', trigger: 'blur' }
  ],
  expiryDate: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (props.isEdit && props.medicineData) {
    Object.assign(medicineForm, {
      id: props.medicineData.id,
      medicineCode: props.medicineData.medicineCode || '',
      name: props.medicineData.name || '',
      genericName: props.medicineData.genericName || '',
      category: props.medicineData.category || 1,
      type: props.medicineData.type || 1,
      specification: props.medicineData.specification || '',
      unit: props.medicineData.unit || '',
      manufacturer: props.medicineData.manufacturer || '',
      approvalNumber: props.medicineData.approvalNumber || '',
      purchasePrice: props.medicineData.purchasePrice || 0,
      sellingPrice: props.medicineData.sellingPrice || 0,
      stockQuantity: props.medicineData.stockQuantity || 0,
      safetyStock: props.medicineData.safetyStock || 10,
      maxStock: props.medicineData.maxStock || 1000,
      productionDate: props.medicineData.productionDate || '',
      expiryDate: props.medicineData.expiryDate || '',
      storageCondition: props.medicineData.storageCondition || '',
      status: props.medicineData.status || 1,
      dosage: props.medicineData.dosage || '',
      indications: props.medicineData.indications || '',
      adverseReactions: props.medicineData.adverseReactions || '',
      contraindications: props.medicineData.contraindications || '',
      precautions: props.medicineData.precautions || '',
      remark: props.medicineData.remark || ''
    })
  }
}

// 处理取消
const handleCancel = () => {
  emit('close')
}

// 处理提交
const handleSubmit = async () => {
  if (!medicineFormRef.value) return
  
  try {
    await medicineFormRef.value.validate()
    submitLoading.value = true
    
    const formData = { ...medicineForm }
    
    let response
    if (props.isEdit) {
      response = await updateMedicine(formData)
    } else {
      response = await addMedicine(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(props.isEdit ? '更新成功' : '添加成功')
      emit('close', 'success', response.data)
    } else {
      ElMessage.error(response.message || (props.isEdit ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交表单错误:', error)
    ElMessage.error(props.isEdit ? '更新失败' : '添加失败')
  } finally {
    submitLoading.value = false
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.medicine-handle {
  padding: 20px 0;
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  position: sticky;
  bottom: 0;
  background: white;
  z-index: 1;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #303133;
}
</style> 